package com.evaluation.kexingcp.psycho.evaluation.sys.excels;

import com.evaluation.kexingcp.admin.api.vo.UserExcelVO;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.*;

import java.io.IOException;
import java.util.List;

public abstract class BaseExcelExport<T> {

    protected final List<String> title;
    protected final XSSFWorkbook workbook;
    protected final XSSFSheet sheet;
    protected HttpServletResponse response;

    public BaseExcelExport(HttpServletResponse response, List<String> title) {
        this.title = title;
        workbook = new XSSFWorkbook();
        //创建工作表sheet
        sheet = workbook.createSheet();
        this.response = response;
    }

    private void writeHeader() {
        //创建第一行
        XSSFRow row = sheet.createRow(0);
        row.setHeightInPoints(30);

        XSSFCell cell = null;
        //插入第一行的表头
        for (int i = 0; i < title.size(); i++) {
            cell = row.createCell(i);
            cell.setCellValue(title.get(i));

            XSSFCellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setAlignment(HorizontalAlignment.CENTER);
            cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
            cellStyle.setBorderLeft(BorderStyle.THIN);//左边框
            cellStyle.setBorderTop(BorderStyle.THIN);//上边框
            cellStyle.setBorderRight(BorderStyle.THIN);//右边框
            cellStyle.setFillBackgroundColor(IndexedColors.GREY_25_PERCENT.index);
            cellStyle.setWrapText(true);
            XSSFFont font =workbook.createFont();
            font.setBold(true);
            cellStyle.setFont(font);
            cell.setCellStyle(cellStyle);
            sheet.setColumnWidth(i, 10 * 256);
        }
    }

    protected abstract void writeData(List<T> data);

    public void doExport(List<T> data) throws IOException {
        writeHeader();
        writeData(data);
        workbook.write(response.getOutputStream());
    }
}
